<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="表号" prop="meterNo">
        <el-input
          v-model="queryParams.meterNo"
          placeholder="请输入表号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="户号" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入户号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="户名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="false">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['meterread:dailyusage:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="waterDataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="户号" align="center" prop="userId" />
      <el-table-column label="户名" align="center" prop="userName" />
      <el-table-column label="地址" align="center" prop="waterAddress" />
      <el-table-column label="表号" align="center" prop="meterNo" />
      <el-table-column label="表读数" align="center" prop="currentReading" />
      <el-table-column label="表底数" align="center" prop="initialReading" />
      <el-table-column label="抄表时间" align="center" prop="readDate" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleInfo(scope.row)"
            v-hasPermi="['meterread:monthusage:hisList']"
          >月用水量统计</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查询日用水量数据 -->
    <el-dialog :title="title" :visible.sync="open" width="1300px" append-to-body @opened="handleDialogOpened" @closed="handleDialogClosed">
      <el-tabs v-model="activeTab" type="border-card" @tab-click="handleTabClick">
        <el-tab-pane label="月用水量数据" name="table">
          <el-table v-loading="hisLoading" :data="dailyusageList">
            <el-table-column label="表号" align="center" prop="meterNo" />
            <el-table-column label="户号" align="center" prop="userId" />
            <el-table-column label="户名" align="center" prop="userName" />
            <el-table-column label="月份" align="center" prop="month" />
            <el-table-column label="月用水量" align="center" prop="monthlyConsumption" />
          </el-table>
          <pagination
            v-show="hisTotal>0"
            :total="hisTotal"
            :page.sync="queryHisParams.pageNum"
            :limit.sync="queryHisParams.pageSize"
            @pagination="getHisList"
          />
        </el-tab-pane>
        <el-tab-pane label="月用水量分析" name="chart">
          <!-- 图表区域 -->
          <div class="chart-container">
            <div class="chart-header">
              <div class="chart-title">{{ currentUser ? currentUser.userName + ' - 用水量趋势分析' : '用水量趋势分析' }}</div>
              <div class="chart-controls" v-if="false">
                <el-select v-model="chartDateRange" placeholder="选择时间范围" size="mini" @change="handleDateRangeChange">
                  <el-option label="近7天" value="7days"></el-option>
                  <el-option label="近30天" value="30days"></el-option>
                  <el-option label="近3个月" value="3months"></el-option>
                  <el-option label="全部数据" value="all"></el-option>
                </el-select>
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-refresh"
                  @click="refreshChart"
                  :loading="chartLoading"
                >刷新</el-button>
              </div>
            </div>
            <div class="chart-info">
              <el-row :gutter="20">
                <el-col :span="6">
                  <div class="info-card">
                    <div class="info-label">平均月用水量</div>
                    <div class="info-value">{{ averageDailyUsage }} 吨</div>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="info-card">
                    <div class="info-label">最高月用水量</div>
                    <div class="info-value">{{ maxDailyUsage }} 吨</div>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="info-card">
                    <div class="info-label">最低月用水量</div>
                    <div class="info-value">{{ minDailyUsage }} 吨</div>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="info-card">
                    <div class="info-label">总用水量</div>
                    <div class="info-value">{{ totalUsage }} 吨</div>
                  </div>
                </el-col>
              </el-row>
            </div>
            <div v-if="chartLoading" class="chart-loading">
              <i class="el-icon-loading"></i>
              <span>图表加载中...</span>
            </div>
            <div v-else-if="!chartDataAvailable" class="chart-no-data">
              <i class="el-icon-picture-outline"></i>
              <span>暂无数据</span>
            </div>
            <div v-else id="waterChart" style="width: 100%; height: 400px;"></div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import { listWaterData,listMonthusage, listMonthusageImg} from "@/api/meterread/monthusage";
import * as echarts from "echarts";

export default {
  name: "Monthusage",
  data() {
    return {
      // 遮罩层
      loading: true,
      hisLoading: true,
      chartLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      hisTotal: 0,
      waterDataList: [],
      // 日用水量表格数据
      dailyusageList: [],
      // 用于图表的所有日用水量数据
      allDailyUsageData: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 激活的标签页
      activeTab: 'table',
      // 当前选择的用户信息
      currentUser: null,
      // 图表日期范围
      chartDateRange: '30days',
      // 图表实例
      waterChart: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        meterNo: null,
        userId: null,
        userName: null,
        readingDate: null,
        dailyConsumption: null,
        currentReading: null,
        previousReading: null,
        readerId: null,
        readerName: null,
      },
      queryHisParams: {
        pageNum: 1,
        pageSize: 10,
        meterNo: null,
        userId: null,
      },
      queryHisImgParams: {
        pageNum: 1,
        pageSize: 36, // 获取更多数据用于图表
        meterNo: null,
        userId: null,
      },
      // 表单参数
      form: {},
      // 图表统计数据
      chartStats: {
        average: 0,
        max: 0,
        min: 0,
        total: 0
      },
      // 表单校验
      rules: {
      }
    };
  },
  computed: {
    chartDataAvailable() {
      return this.allDailyUsageData && this.allDailyUsageData.length > 0;
    },
    averageDailyUsage() {
      return this.chartStats.average.toFixed(2);
    },
    maxDailyUsage() {
      return this.chartStats.max.toFixed(2);
    },
    minDailyUsage() {
      return this.chartStats.min.toFixed(2);
    },
    totalUsage() {
      return this.chartStats.total.toFixed(2);
    }
  },
  created() {
    this.getList();
  },
  mounted() {
    // 响应窗口大小变化，调整图表尺寸
    window.addEventListener('resize', this.resizeChart);
  },
  beforeDestroy() {
    // 清理事件监听器
    window.removeEventListener('resize', this.resizeChart);
    // 销毁图表实例
    if (this.waterChart) {
      this.waterChart.dispose();
    }
  },
  methods: {
    // 初始化图表
    initChart() {
      const chartDom = document.getElementById('waterChart');
      if (!chartDom) return;

      this.waterChart = echarts.init(chartDom);
      // 设置基础配置
      const option = {
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#ddd',
          borderWidth: 1,
          textStyle: {
            color: '#333'
          },
          formatter: function(params) {
            let result = `<div style="font-weight: bold; margin-bottom: 5px;">${params[0].axisValue}</div>`;
            params.forEach(item => {
              result += `<div>
                <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${item.color}"></span>
                ${item.seriesName}: <span style="font-weight: bold; color: ${item.color}">${item.value} 吨</span>
              </div>`;
            });
            return result;
          }
        },
        legend: {
          data: ['月用水量'],
          bottom: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: [],
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          },
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '用水量(吨)',
          min: 0,
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#f0f0f0',
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: '月用水量',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            itemStyle: {
              color: '#409EFF'
            },
            lineStyle: {
              width: 3,
              color: '#409EFF'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(64, 158, 255, 0.6)' },
                { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
              ])
            },
            markPoint: {
              data: [
                { type: 'max', name: '最大值' },
                { type: 'min', name: '最小值' }
              ]
            },
            markLine: {
              data: [
                { type: 'average', name: '平均值' }
              ]
            },
            data: []
          }
        ]
      };
      this.waterChart.setOption(option);
    },

    // 处理后端数据为图表数据
    processChartData() {
      if (!this.allDailyUsageData || this.allDailyUsageData.length === 0) {
        return { dates: [], values: [] };
      }

      // 按日期排序
      const sortedData = [...this.allDailyUsageData].sort((a, b) => {
        return new Date(a.month) - new Date(b.month);
      });

      // 根据选择的时间范围过滤数据
      let filteredData = sortedData;
      /*if (this.chartDateRange !== 'all') {
        const days = this.chartDateRange === '7days' ? 7 :
          this.chartDateRange === '30days' ? 30 : 90;

        const cutoffDate = new Date();
        cutoffDate.setDate(cutoffDate.getDate() - days);

        filteredData = sortedData.filter(item => {
          const itemDate = new Date(item.readingDate);
          return itemDate >= cutoffDate;
        });
      }*/

      // 提取日期和用水量
      const dates = filteredData.map(item => item.month);
      const values = filteredData.map(item => parseFloat(item.monthlyConsumption) || 0);

      return { dates, values };
    },

    // 计算统计数据
    calculateStats(values) {
      if (!values || values.length === 0) {
        return { average: 0, max: 0, min: 0, total: 0 };
      }

      const sum = values.reduce((a, b) => a + b, 0);
      const max = Math.max(...values);
      const min = Math.min(...values);
      const average = sum / values.length;

      return {
        average,
        max,
        min,
        total: sum
      };
    },

    // 加载图表数据
    loadChartData() {
      if (!this.open) return;

      this.chartLoading = true;
      try {
        // 处理后端数据为图表格式
        const chartData = this.processChartData();

        // 计算统计数据
        this.chartStats = this.calculateStats(chartData.values);

        // 更新图表
        if (this.waterChart) {
          this.waterChart.setOption({
            xAxis: {
              data: chartData.dates
            },
            series: [{
              data: chartData.values
            }]
          });
        }
      } catch (error) {
        console.error('加载图表数据失败:', error);
        this.$message.error('图表数据加载失败');
      } finally {
        this.chartLoading = false;
      }
    },

    // 调整图表尺寸
    resizeChart() {
      if (this.waterChart) {
        this.waterChart.resize();
      }
    },

    // 刷新图表
    refreshChart() {
      this.loadChartData();
    },

    // 处理日期范围变化
    handleDateRangeChange() {
      this.loadChartData();
    },

    // 对话框打开后回调
    handleDialogOpened() {
      this.$nextTick(() => {
        if (this.activeTab === 'chart') {
          this.initChart();
          this.loadChartData();
        }
      });
    },

    // 对话框关闭后回调
    handleDialogClosed() {
      if (this.waterChart) {
        this.waterChart.dispose();
        this.waterChart = null;
      }
      this.activeTab = 'table';
      this.currentUser = null;
      this.allDailyUsageData = [];
    },

    // 标签页点击事件
    handleTabClick(tab) {
      if (tab.name === 'chart') {
        this.$nextTick(() => {
          this.initChart();
          this.loadChartData();
        });
      }
    },

    /** 查询水表数据列表 */
    getList() {
      this.loading = true;
      listWaterData(this.queryParams).then(response => {
        this.waterDataList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    /** 查询日用水量数据列表 */
    getHisList() {
      this.hisLoading = true;
      listMonthusage(this.queryHisParams).then(response => {
        this.dailyusageList = response.rows;
        this.hisTotal = response.total;
        this.hisLoading = false;
      }).catch(() => {
        this.hisLoading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        meterNo: null,
        userId: null,
        userName: null,
        readingDate: null,
        dailyConsumption: null,
        currentReading: null,
        previousReading: null,
        readerId: null,
        readerName: null,
        createBy: null,
        createTime: null
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 日用水量历史数据 */
    handleInfo(row) {
      this.currentUser = row;
      this.queryHisParams.pageNum = 1;
      this.queryHisParams.pageSize = 10;
      this.queryHisParams.meterNo = row.meterNo;
      this.queryHisParams.userId = row.userId;
      this.hisLoading = true;
      this.queryHisImgParams.meterNo = row.meterNo;
      listMonthusageImg(this.queryHisImgParams).then(response => {
        // 保存所有数据用于图表展示
        this.allDailyUsageData = response.rows;
        this.hisLoading = false;
      }).catch(() => {
        this.hisLoading = false;
      });
      listMonthusage(this.queryHisParams).then(response => {
        this.dailyusageList = response.rows;
        this.hisTotal = response.total;
        this.open = true;
        this.title = `${row.userName} - 日用水量统计`;
        this.hisLoading = false;
      }).catch(() => {
        this.hisLoading = false;
        this.$message.error('获取日用水量数据失败');
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('monthusage/monthusage/export', {
        ...this.queryParams
      }, `monthusage_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
/** 表格布局 **/
.pagination-container {
  position: relative;
  height: 35px;
  margin-bottom: 10px;
  margin-top: 15px;
  padding: 10px 20px !important;
}
.chart-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.chart-controls {
  display: flex;
  gap: 10px;
}

.chart-info {
  margin-bottom: 20px;
}

.info-card {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 15px;
  text-align: center;
  border-left: 4px solid #409EFF;
}

.info-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.info-value {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.chart-loading, .chart-no-data {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 400px;
  color: #999;
  font-size: 14px;
}

.chart-loading i, .chart-no-data i {
  font-size: 48px;
  margin-bottom: 10px;
}

::v-deep .el-tabs__content {
  padding: 0;
}

::v-deep .el-tab-pane {
  padding: 0;
}
</style>
